<template>
  <view class="container">
    <view class="title">创建人脸模型</view>

    <!-- 预览区域 -->
    <view v-if="previewImage" class="image-preview">
      <image :src="previewImage" mode="aspectFit" class="preview-img"></image>
    </view>

    <view v-else class="placeholder" @click="chooseImage">
      <text class="icon">📷</text>
      <text class="tip">点击上传人脸照片</text>
    </view>

    <!-- 操作按钮 -->
    <button class="btn" :disabled="!previewImage || uploading" @click="uploadImage">
      {{ uploading ? '上传中...' : '确认创建人脸模型' }}
    </button>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { createDriverFaceModelAPI } from '@/services/home'
import type { DriverFaceModelForm } from '@/types/home'

// 响应式数据
const previewImage = ref('')
const imageBase64 = ref('' as string)
const uploading = ref(false)
const query = defineProps<{
  openId: string
  sessionKey: string
}>()
const openId = ref(query.openId)

// 页面加载
onMounted(() => {
  if (!openId.value) {
    uni.showToast({ title: '未登录', icon: 'none', duration: 2000 })
    setTimeout(() => uni.navigateBack(), 1500)
  }
})

// 1. 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 1,
    sourceType: ['camera', 'album'],
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0]
      previewImage.value = tempFilePath
      await convertImageToBase64(tempFilePath)
    },
    fail: (err) => {
      if (!err.errMsg.includes('cancel')) {
        uni.showToast({ title: '选择图片失败', icon: 'none' })
      }
    },
  })
}

// 2. 将图片转为 Base64（兼容小程序和 H5）
const convertImageToBase64 = (tempFilePath: any) => {
  return new Promise((resolve, reject) => {
    if (uni.getFileSystemManager) {
      // 小程序平台
      const fs = uni.getFileSystemManager()
      fs.readFile({
        filePath: tempFilePath,
        encoding: 'base64',
        success: (res: any) => {
          imageBase64.value = res.data
          resolve(res.data)
        },
        fail: (err) => {
          uni.showToast({ title: '读取图片失败', icon: 'none' })
          reject(err)
        },
      })
    }
  })
}

// 3. 上传并创建人脸模型
const uploadImage = async () => {
  if (!imageBase64.value) {
    uni.showToast({ title: '请先选择照片', icon: 'none' })
    return
  }

  uploading.value = true

  try {
    const params: DriverFaceModelForm = {
      openId: openId.value,
      imageBase64: imageBase64.value,
    }

    const res = await createDriverFaceModelAPI(params)

    if (res.data) {
      uni.showToast({
        title: '人脸模型创建成功',
        icon: 'success',
        duration: 2000,
        success: () => {
          uni.navigateTo({
            url:
              '/pages/login/login?openId=' +
              query.openId +
              '&sessionKey=' +
              query.sessionKey +
              '&verify=0',
          })
        },
      })
    } else {
      uni.showToast({
        title: '创建失败',
        icon: 'none',
        duration: 2000,
      })
    }
  } catch (error) {
    uni.showToast({
      title: '请求失败，请重试',
      icon: 'none',
      duration: 2000,
    })
    console.error('创建人脸模型失败:', error)
  } finally {
    uploading.value = false
  }
}
</script>

<style scoped>
.container {
  padding: 40rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 60rpx;
  color: #333;
}

.placeholder {
  width: 80%;
  height: 400rpx;
  margin: 0 auto 60rpx;
  border: 2rpx dashed #ccc;
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #fafafa;
  color: #999;
}

.icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.tip {
  font-size: 28rpx;
}

.image-preview {
  width: 80%;
  height: 400rpx;
  margin: 0 auto 60rpx;
  overflow: hidden;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.preview-img {
  width: 100%;
  height: 100%;
}

.btn {
  width: 80%;
  margin: 0 auto;
  background-color: #007aff;
  color: #fff;
  font-size: 32rpx;
  border-radius: 80rpx;
}

.btn:disabled {
  background-color: #ccc;
}
</style>
